<?php

namespace app\common\services;

use app\common\exceptions\ErrException;
use app\common\umeng\notification\android\AndroidUnicast;
use app\common\umeng\notification\ios\IOSUnicast;

class UmengPushService
{
    /**
     * @var 苹果友盟配置
     */
    protected $iosAppKey            = NULL;
    protected $iosAppSecret         = NULL;
    protected $timestamp            = NULL;
    /**
     * @var 安卓友盟配置
     */
    protected $androidAppKey        = NULL;
    protected $androidMessageSecret = NULL;
    protected $androidAppSecret     = NULL;
    protected $extra                = ['message_type' => 'system_notice'];

    /**
     * @var Member
     */
    protected $memberModel;

    /**
     * @var MemberNotice
     */
    protected $memberNoticeModel;

    /**
     * @var \Redis
     */
    protected $redisService;

    /**
     * @var string
     */
    protected $noticeRedisKey;

    public function __construct($iosAppKey = '',$iosAppSecret = '',$androidAppKey = '',$androidMessageSecret = '',$androidAppSecret = ''){
        // ios
        $this->iosAppKey            = $iosAppKey?:env('umeng.iosAppKey');
        $this->iosAppSecret         = $iosAppSecret?:env('umeng.iosAppSecret');
        // Android
        $this->androidAppKey        = $androidAppKey?:env('umeng.androidAppKey');
        $this->androidMessageSecret = $androidMessageSecret?:env('umeng.androidAppSecret');
        $this->androidAppSecret     = $androidAppSecret?:env('umeng.androidAppSecret');
        $this->timestamp            = strval(time());
        $this->noticeRedisKey       = 'userNoticePush:';
    }

    function sendAndroidUnicast(string $device_token = '', string $title = '', string $content = '', string $sound = 'chime') {
        try {
            $unicast = new AndroidUnicast();
            $unicast->setAppMasterSecret($this->androidMessageSecret);
            $unicast->setPredefinedKeyValue("appkey", $this->androidAppKey);
            $unicast->setPredefinedKeyValue("timestamp", $this->timestamp);
            // Set your device tokens here

            $unicast->setPredefinedKeyValue("device_tokens", $device_token);
            $unicast->setPredefinedKeyValue("ticker", "Android unicast ticker");
            $unicast->setPredefinedKeyValue("title", $title);
            $unicast->setPredefinedKeyValue("text",  $content);
            $unicast->setPredefinedKeyValue("type", "listcast");
            $unicast->setPredefinedKeyValue("mipush", true);
            $unicast->setPredefinedKeyValue("display_type",'notification');
            if (!empty($sound)) {
                $unicast->setPredefinedKeyValue("play_sound", true);
                $unicast->setPredefinedKeyValue("sound", $sound);
            }

            $unicast->setPredefinedKeyValue("description", "线上正式测试");
            $unicast->setPredefinedKeyValue("mi_activity", "com.maiyun.myunskymeet.codes.activitys.splashs.SplashActivity");
            $policy = [
                'expire_time' => date('Y-m-d H:i:s', time() + 60),
            ];
            $unicast->setPredefinedKeyValue("policy", $policy);
            $unicast->setPredefinedKeyValue("production_mode", "false");


            $unicast->setPredefinedKeyValue("after_open",       "go_app");
            // Set 'production_mode' to 'false' if it's a test device.
            // For how to register a test device, please see the developer doc.
            $unicast->setPredefinedKeyValue("production_mode", "true");
            // Set extra fields
            $unicast->setExtraField(key($this->extra),value($this->extra));
            $unicast->send();

        } catch (\Exception $e) {
            ErrException::throwExcep($e->getCode(), $e->getMessage());
        }
    }

    function sendIOSUnicast(string $device_token = '', string $title = '', string $content = '', string $sound = 'chime',$ext)
    {
        try {
            $unicast = new IOSUnicast();
            $unicast->setAppMasterSecret($this->iosAppSecret);
            $unicast->setPredefinedKeyValue("appkey",    $this->iosAppKey);
            $unicast->setPredefinedKeyValue("timestamp", $this->timestamp);
            // Set your device tokens here
            $unicast->setPredefinedKeyValue("device_tokens", $device_token);
            $unicast->setPredefinedKeyValue("alert", $title);
            $unicast->setPredefinedKeyValue("badge", 0);
            $unicast->setPredefinedKeyValue("sound", $sound);
            // Set 'production_mode' to 'true' if your app is under production mode
            $unicast->setPredefinedKeyValue("production_mode", "true");
            // Set customized fields
            $unicast->setCustomizedField("test", $content);
            if(is_array($ext) && !empty($ext)){
                foreach ($ext as $key => $value){
                    $unicast->setCustomizedField($key, $value);
                }
            }
            $unicast->send();
        } catch (ErrException $e) {
            ErrException::throwExcep($e->getCode(), $e->getMessage());
        }
    }

    /**
     * Push设备友盟消息
     * @param string $device_tokens
     * @param string $os_type
     * @param string $title
     * @param string $content
     * @param string $sound
     * @return bool|string|null
     * @Function:sendEquipmentUmengPush
     * @Date: 2022/12/6
     * @Time: 18:25
     */
    public function sendEquipmentUmengPush(string $device_tokens, string $os_type = 'ios', string $title = '', string $content,$ext = [], string $sound = 'chime')
    {
        $res = false;
        try {
            switch ($os_type)
            {
                case 'ios':
                    $res = $this->sendIOSUnicast($device_tokens, $title, $content, $sound,$ext);
                    break;
                case 'Android':
                    $res = $this->sendAndroidUnicast($device_tokens, $title, $content, $sound,$ext);
                    break;
            }
        }catch (\Throwable $e){
            return true;
        }
        return $res;
    }

    /**
     * 发送用户PUSH
     * @param int $member_id
     * @param string $head_img
     * @param string $title
     * @param string $content
     * @param int $type
     * @return bool|void
     * @Function:addUserPushNotice
     * @Date: 2022/12/12
     * @Time: 21:40
     * @throws ErrException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function addUserPushNotice($db,$redisDb,int $member_id = 0, string $head_img = '', string $title = '系统通知', string $content = '', int $type = 0)
    {
        if ($type == 0){
            $type =7; // 恢复默认值
        }
        $user = $db->table('member')->where('id', $member_id)->field('os_system, device_tokens')->find();
        /*        // 保持友盟设备token唯一
                if ($this->memberModel->where('device_tokens', $user->device_tokens)->value('id'))
                {
                    // 清除其他账号相同设备token
                    $this->memberModel->update(['device_tokens' => ''], [
                        ['id', '<>', $member_id],
                        ['device_tokens', '=', $user->device_tokens],
                    ]);
                }*/
        $data = [
            'member_id'   => $member_id,
            'head_img'    => 'https://qn.365feicui.cn/public/notice.png',
            'content'     => $content,
            'type'        => $type,   // 消息类型 (1. 充值月卡 2. 充值年卡 3. 客户投诉 4. VIP即将到期  5. 流量充值成功提醒  6. 流量余额不足提醒，7.季卡)
            'create_time' => time()
        ];
        $res  = $db->table('member_notice')->insert($data);
        // 设置Redis未读消息数
        $res1 = $redisDb->setIncrbyBucket($this->noticeRedisKey . $member_id);
        if (empty($user['device_tokens'])) return false;
        try {
            // 友盟推送
            $res2 = $this->sendEquipmentUmengPush($user->device_tokens, $user->os_system?$user->os_system:'ios', $title, $content,['type'=>$type]);
            if ($res && $res1 && $res2) return true;
        }catch (\Throwable $e){
        }
        return true;
    }

}
